<?php

namespace app\common\model;

class NewsSee extends Base
{

    protected $deleteTime = "delete_time";

    /**
     * @param string $openid
     * @param int $news_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setNewsSeeByUser(string $openid = "", int $news_id = 0): bool
    {
        $row = $this->where('openid', $openid)
            ->where('news_id', $news_id)
            ->find();
        if ($row) {
            return true;
        } else {
            $result = $this->save([
                "openid" => $openid,
                "news_id" => $news_id
            ]);
            if ($result) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * @param int $news_id
     * @return mixed
     */
    public function getUserByCount(int $news_id = 0){
        return $this->field('id,count(*) as count')
            ->where('news_id',$news_id)
            ->group('openid')
            ->find();
    }

    /**
     * @param int $news_id
     * @return NewsSee|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getSeeByCount(int $news_id = 0){
        return $this->field('id,count(*) as count')
            ->where('news_id',$news_id)
            ->find();
    }
}